#!/usr/bin/python3

import urllib
import down_dybee_film
import uapool
import re
import getopt
import sys
import zjl_util

"""
这是下载 xbshare 网站在线播放视频
example:
视频地址：
1、访问：http://www.xbshare.cc/v-3auz-fuyjac.html，获取 siteLink:"a5FzBNrU4wlyOu0lRPa+rA0JbgKZA7JctJduPkifle6rmh1sJkA4MEEKCxj5BX6Bk6j0EdGRUDqCmSkV3BrZVA==" ec:"ltnz" ；关键值：siteLink， ec
2、访问：https://r.yskanba.com/analysis/index?eurl=a5FzBNrU4wlyOu0lRPa%2BrA0JbgKZA7JctJduPkifle6rmh1sJkA4MEEKCxj5BX6Bk6j0EdGRUDqCmSkV3BrZVA%3D%3D&ec=ltnz  （使用sitelink和ec参数）
    获取m3u8地址： https://yi.jingdianzuida.com/20191204/PEzy1pmM/index.m3u8
3、访问m3u8地址，获取到uri: /ppvod/4FF9A4237618EBE06633C9CC6E659BB4.m3u8
4、访问真正m3u8地址： https://yi.jingdianzuida.com/ppvod/4FF9A4237618EBE06633C9CC6E659BB4.m3u8
5、得到ts的uri 列表，如: /20191204/PEzy1pmM/1000kb/hls/dlSpfePI7784002.ts
6、下载ts并合并 
"""


def down_all_video(index_url, dir_path, offset):
    index_info = get_video_urls(index_url)
    title = index_info['title']
    video_urls = index_info['urls']
    dir_path = dir_path + '/' + title

    for i in range(offset, len(video_urls)):
        u = video_urls[i]
        video_param = get_sitelink_ec(u)
        m3u8_url = get_m3u8_url(video_param)

        d = down_dybee_film.dybee()
        file_name = video_param['title'] + '.ts'
        print('----------开始下载：' + video_param['title'] + '----------')
        d.down_file(m3u8_url, dir_path, file_name)
        print('----------下载完成：' + video_param['title'] + '----------')


def get_video_urls(index_url):
    """
    获取每一集的地址,并下载视频
    http://www.xbshare.cc/a-3auz.html
    :param index_url:
    :return:
    """
    doc = zjl_util.get_doc(index_url)
    pat_play_list = 'class="play-list(.*?)</ul>'
    ul = re.compile(pat_play_list, re.S).findall(doc)[0]
    pat_video_url = '"(http.*?)"'
    urls = re.compile(pat_video_url).findall(ul)

    pat_title = '<title>(.*?)</title>'
    title_str = re.compile(pat_title, re.S).findall(doc)[0]
    pat_title2 = '《(.*?)》'
    title = re.compile(pat_title2).findall(title_str)[0]

    result = {'title': title, 'urls': urls}

    return result


def get_sitelink_ec(video_url):
    """
    1、访问：http://www.xbshare.cc/v-3auz-fuyjac.html，获取 siteLink:"a5FzBNrU4wlyOu0lRPa+rA0JbgKZA7JctJduPkifle6rmh1sJkA4MEEKCxj5BX6Bk6j0EdGRUDqCmSkV3BrZVA==" ec:"ltnz" ；关键值：siteLink， ec
    :param video_url:
    :return:
    """
    uapool.UA()
    doc = zjl_util.get_doc(video_url)
    pat_sitelink = 'siteLink:"(.*?)"'
    sitelink = re.compile(pat_sitelink).findall(doc)
    pat_ec = 'ec:"(.*?)"'
    ec = re.compile(pat_ec).findall(doc)
    pat_title = 'PlayName:"(.*?)"'
    title = re.compile(pat_title).findall(doc)
    result = {'sitelink': sitelink[0], 'ec': ec[0], 'title': title[0]}
    return result


def get_m3u8_url(video_param):
    """
    2、访问：https://r.yskanba.com/analysis/index?eurl=a5FzBNrU4wlyOu0lRPa%2BrA0JbgKZA7JctJduPkifle6rmh1sJkA4MEEKCxj5BX6Bk6j0EdGRUDqCmSkV3BrZVA%3D%3D&ec=ltnz  （使用sitelink和ec参数）
    获取m3u8地址： https://yi.jingdianzuida.com/20191204/PEzy1pmM/index.m3u8
    3、访问m3u8地址，获取到uri: /ppvod/4FF9A4237618EBE06633C9CC6E659BB4.m3u8
    4、访问真正m3u8地址： https://yi.jingdianzuida.com/ppvod/4FF9A4237618EBE06633C9CC6E659BB4.m3u8
    5、得到ts的uri 列表，如: /20191204/PEzy1pmM/1000kb/hls/dlSpfePI7784002.ts
    :param video_param:
    :return:
    """

    form_data = {
        'eurl': video_param['sitelink'],
        'ec': video_param['ec']
    }
    param = urllib.parse.urlencode(form_data)
    analysis_url = 'https://r.yskanba.com/analysis/index?' + param
    cookie = ("Host", 'r.yskanba.com')
    headers = [cookie]
    uapool.set_header(headers)
    doc = zjl_util.get_doc(analysis_url)
    m3u8_pat = 'url=(.*?m3u8)'
    # print(doc)
    m3u8 = re.compile(m3u8_pat).findall(doc)

    m3u8_url = ''
    if len(m3u8) == 0:
        # 不是网站自己的资源，不能直接获取的m3u8地址
        pat_old_ulr = "oldUlr='(.*?)'"
        old_urls = re.compile(pat_old_ulr).findall(doc)
        # print('--------------' + str(old_urls) + '--------------')
        # 第三方去解析它
        jx_url = 'https://jx.618g.com/?url=' + old_urls[0]
        jx_doc = zjl_util.get_doc(jx_url)
        # print(jx_doc)
        pat_m3u8 = 'url=(.*?m3u8)'
        m3u8 = re.compile(pat_m3u8).findall(jx_doc)
        # print('第三方解析：' + str(m3u8))
        m3u8_url = m3u8[0]
    else:
        m3u8_url = m3u8[0]
    doc = zjl_util.get_doc(m3u8_url)
    m3u8_pat = '(.*?m3u8)'
    m3u8_uris = re.compile(m3u8_pat).findall(doc)

    print(m3u8_uris)
    m3u8_uri = m3u8_uris[len(m3u8_uris) - 1]
    m3u8_full_url = ''
    if str(m3u8_uri).startswith('/'):
        base_url = uapool.get_base_url(m3u8_url)
        m3u8_full_url = base_url + m3u8_uris[0]
    else:
        r_index = m3u8_url.rindex('/')
        m3u8_full_url = m3u8_url[0: r_index+1] + m3u8_uris[0]
    return m3u8_full_url


def main():
    """
    下载 xbshare 的在线视频
    :return:
    """

    '''这里是默认值'''
    index_url = 'http://www.xbshare.cc/a-3auz.html'
    dir_path = '/home/long655113/download'
    offset = 0

    opts, args = getopt.getopt(sys.argv[1:], "hu:", ["dir=", "offset="])
    for o, a in opts:
        if o == '-h':
            print("python3 xbshare_down.py -u " + index_url + " --dir=" + dir_path + " --offset=" + str(offset))
            exit()
        if o == '-u':
            index_url = a
        if o == '--dir':
            dir_path = a
        if o == '--offset':
            offset = int(a)
    print('目录地址：' + index_url)
    print('保存路径：' + dir_path)
    down_all_video(index_url, dir_path, offset)


if __name__ == "__main__":
    main()
